package com.lyj.threads;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 线程池参数
 */
@Data
public class SinglePoolParam {

    Logger logger = LoggerFactory.getLogger(SinglePoolParam.class);
    /**
     * 当前线程池的参数大小、核心线程数
     */
    private int poolSize = 5;
    /**
     * 当前线程池最大处理数
     */
    private int maxTaskSize = 5;

    /**
     * 当前线程池最大队列数
     */
    private int workQueueSize = 5;

    /**
     * 线程池对象
     */
    private ThreadPoolExecutor executor = null;

    /**
     * 线程池名称
     */
    private String poolName = null;

    public SinglePoolParam() {
    }

    public SinglePoolParam(String poolName,int poolSize, int maxTaskSize, int workQueueSize ) {
        this.poolSize = poolSize;
        this.maxTaskSize = maxTaskSize;
        this.workQueueSize = workQueueSize;
        this.poolName = poolName;
        CustomerThreadPoolExecutor executor = new CustomerThreadPoolExecutor(poolSize,maxTaskSize,workQueueSize);
        this.executor = executor.getCommonThreadPoolExecutor();
    }

    public SinglePoolParam(String poolName) {
        this.poolName = poolName;
        CustomerThreadPoolExecutor execu = null;
        // 使用指定的拒绝策略创建线程池
        execu = new CustomerThreadPoolExecutor(poolSize, maxTaskSize,workQueueSize);
        this.executor = execu.getCommonThreadPoolExecutor();
    }

    /**
     * 将指定线程放入线程池
     */
    public void put(Thread thread) {
        logger.info(noePoolStatus("thread name["+ thread.getName() + "] 》》》》》》》》》》》》》》》线程开始执行《《《《《《《《《《《《《《《《"));
        // 执行线程
        executor.execute(thread);
    }

    public String noePoolStatus(String memo) {
        BlockingQueue<Runnable> queue = this.executor.getQueue();
        return Thread.currentThread().getName()
                + this.poolName + "线程池 " + memo + "：core-" + this.executor.getCorePoolSize()
                + " max-" + this.executor.getMaximumPoolSize()
                + " active-" + this.executor.getActiveCount()
                + " finish-" + this.executor.getCompletedTaskCount()
                + " queue-" + (queue.size()+queue.remainingCapacity())
                + " waitqueuq-" + queue.size();
    }

    /**
     * 关闭线程池
     */
    public void stop() {
        this.executor.shutdown();
    }


}
